﻿namespace SupplyChainWeb.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;

    /// <summary>
    /// Defines the <see cref="CheckLogin" />
    /// </summary>
    public sealed class CheckLogin : Attribute
    {
        /// <summary>
        /// Defines the IsNeedLogin
        /// </summary>
        public bool IsNeedLogin = false;

        /// <summary>
        /// Initializes a new instance of the <see cref="CheckLogin"/> class.
        /// </summary>
        /// <param name="isNeed">The isNeed<see cref="bool"/></param>
        public CheckLogin(bool isNeed)
        {
            this.IsNeedLogin = isNeed;
        }
    }

    /// <summary>
    /// Defines the <see cref="BaseController" />
    /// </summary>
    public class BaseController : Controller
    {
        /// <summary>
        /// The OnActionExecuting
        /// </summary>
        /// <param name="filterContext">The filterContext<see cref="ActionExecutingContext"/></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            bool result = false;

            //controller上是否有特性CheckLogin，以及特性的IsNeedLogin值
            var controllerAttrs = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(CheckLogin), false);
            if (controllerAttrs.Count() > 0)
            {
                var conAttr = controllerAttrs[0] as CheckLogin;
                if (conAttr != null)
                {
                    if (conAttr.IsNeedLogin)
                        result = true;
                    else
                        result = false;
                }
            }

            //action上是否有特性CheckLogin，以及特性的IsNeedLogin值
            var actionAttrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckLogin), false);
            if (actionAttrs.Count() > 0)
            {
                var attr = actionAttrs[0] as CheckLogin;
                if (attr != null)
                {
                    if (attr.IsNeedLogin)
                        result = true;
                    else
                        result = false;
                }
            }

            if (!IsLogin() && result)
            {
                //如果没有登录，则跳至登陆页
                filterContext.Result = Redirect("/Account/Login");
            }
        }

        /// <summary>
        /// The IsLogin
        /// </summary>
        /// <returns>The <see cref="bool"/></returns>
        protected bool IsLogin()
        {
            if (Session["LoginModel"] != null)
                return true;

            return false;
        }
    }
}
